function windowToCanvas(canvas,x,y){
    /**
        在canvas对象上调用getBoundingClientRect()方法，
        来获取canvas元素的边界框，
        该边界框的坐标是相对于整个窗口的。
        然后返回一个对象，该对象的x、y属性分别对应于鼠标在canvas之中的坐标
    **/
    var bbox=canvas.getBoundingClientRect();
    return {x:x-bbox.left*(canvas.width/bbox.width),
                     y:y-bbox.top*(canvas.height/bbox.height)
                 };
}

class Timeshistory {

    ctx = null; //canvas 绘图对象
    cx = -400;  // canvas 坐标轴中心点x
    cy = 0;  // canvas 坐标轴中心点y
    _w = 0;  // canvas 画布宽度 
    _h = 0;  // canvas 画布高度
    canvas = null ;
    element = null ;
    options = {
        year:[2012,2013,2014,2015,2016,2017,2018,2019,2020],
        data:[]
    }

    position = {}


    constructor(){

    }

    init(element){
      this.element = element;  
      let _w = element.offsetWidth;
      let _h = element.offsetHeight;  
      let canvas = this.canvas = document.createElement('canvas');
      canvas.style.width = _w + 'px';
      canvas.style.height = _h + 'px';
      canvas.style.cursor = 'pointer';
      canvas.width = _w;
      canvas.height = _h;
      element.style.position = 'relative';
      element.append(canvas);
      this.ctx = canvas.getContext('2d');
      this._w = _w;
      this._h = _h;
      // 绑定事件   
      this._bindEvent(element)

      return this;
    }

    // 清屏
    clearScreen(){
        let ctx = this.ctx,_w = this._w,_h = this._h;
        ctx.clearRect(0,0,_w,_h);  
    }

    // 绑定事件
    _bindEvent(){
        //监听鼠标移动事件
            var $this = this;
            var down = false;
            var startPos = {x:0,y:0};
            var cx = this.cx;
            this.canvas.onmousedown = function(e){
                down = true;
                var loc=windowToCanvas($this.canvas,e.clientX,e.clientY);
                startPos = {x:loc.x,y:loc.y}
                cx = $this.cx;
            }
            document.onmouseup = function(){
                down = false;
                startPos = {x:0,y:0};
                cx = $this.cx
            }
            let timers = null;
			this.canvas.onmousemove=function(e){
                var loc=windowToCanvas($this.canvas,e.clientX,e.clientY);
                //console.log(loc);
                //console.log('x='+e.clientX+' y='+e.clientY);
               
                if(down){
                    let Dx = loc.x - startPos.x;
                    $this.cx = cx + Dx;

                    // 重绘图
                    $this.restoreDraw();
                }else{
                    let show = false
                    if(timers) clearTimeout(timers);
                    timers = setTimeout(()=>{
                        console.log($this.dataInfoList)
                        for(let i =0;i< $this.dataInfoList.length;i++){
                            let dataInfoItem = $this.dataInfoList[i];
                            // 简单做了一下区间
                            if(dataInfoItem.cx + dataInfoItem.x <= loc.x+15 && dataInfoItem.cx + dataInfoItem.x >= loc.x -15 && loc.y > 15 && loc.y < dataInfoItem.y*2 -15){
                                $this.showTooltip(dataInfoItem,loc.y,loc.x);
                                show = true;
                                break;
                            }
                        }
                        // 隐藏
                        if(!show){
                            $this.hideTooltip();
                        }
                    },10)
                   
                    
                }
            }
    }

    hideTooltip(){
        if(this.element){
            if(this.tooltip){
                this.tooltip.style.display = 'none';
            }
        }
    }

    showTooltip(dataItem,top,left){
        if(this.element){
            if(!this.tooltip){
                this.tooltip = document.createElement('div')
                this.element.append(this.tooltip);
                this.tooltip.style.position = 'absolute';
                this.tooltip.style.padding = '10px 15px';
                this.tooltip.style.background = 'rgba(38,38,38,0.6)';
                this.tooltip.style.color = '#fff';   
                this.tooltip.style.zIndex = '100';
                this.tooltip.style.pointerEvents = 'none'; 
                this.tooltip.style.transition = 'all 0.3s';
                this.tooltip.style.userSelect = 'none';
            }
            this.tooltip.innerHTML = dataItem.text;
            this.tooltip.style.top = top + 'px';
            this.tooltip.style.left = left + 'px';
            this.tooltip.style.display = 'block';

        }
    }

    drawSplipt(){
        let ctx = this.ctx,_h = this._h ,_w =this._w,cx = this.cx , cy = this.cy;
        let sp = 10;
        
        let bLine = 13;
        let mLine = 7
        let lLine = 3;

        // 刻度时间轴显示范围
        var index = 0;
        var length = (20 >= this.options.year.length*2 + 2 ? 20 : this.options.year.length*2 + 2);
        while(index <= length){
            let count = 0;
            while(count <10){
                ctx.save();
                ctx.beginPath();
                ctx.scale(0.5,1);
                ctx.strokeStyle = '#fff';
                ctx.lineWidth = 1;
                ctx.moveTo(cx*2 + index*100 + count*sp+0.5,_h/2);
                if(count % 10  == 0){
                     ctx.lineTo(cx*2 + index*100 + count*sp+0.5,_h/2 + bLine );
                }else{
                    if(count % 5 == 0){
                         ctx.lineTo(cx*2 + index*100 + count*sp+0.5,_h/2 + mLine);
                    }else{
                        ctx.lineTo(cx*2 + index*100 + count*sp+0.5,_h/2 + lLine);
                    }
                }
                ctx.stroke();
                ctx.restore();
                count++ ;
            }
            index ++;
        }
    }

    drawYear() {
        let ctx = this.ctx,_h = this._h ,_w =this._w,cx = this.cx , cy = this.cy;
        let year = this.options.year;
        ctx.save();
       
        // 便利数据年
        year.forEach((year,index) =>{
            ctx.fillStyle = "#98caec";               //设置填充颜色为紫色
            ctx.font = '10px "微软雅黑"';           //设置字体
            ctx.textBaseline = "bottom";            //设置字体底线对齐绘制基线
            ctx.textAlign = "left";                 //设置字体对齐的方式
            let fontW = ctx.measureText(year + '年').width
            ctx.fillText(year + '年', cx + (index) * 100 +50 - fontW/2, _h/2 - 10);
            this.position[year] = (index) * 100 + 50;
        })
        ctx.restore();
        //console.log(this.position)
    }

    drawData() {
        let data = this.options.data;
        let ctx = this.ctx,_h = this._h ,_w =this._w,cx = this.cx , cy = this.cy;    
        this.dataInfoList = [];
        data.forEach((item,index) => {
            this.dataInfoList.push(
                new Datainfo({
                    ctx,
                    cx,
                    cy,
                    x:this.position[item.year],
                    y:_h/2,
                    text:item.text,
                    index
                })
            )
        })
        this.dataInfoList.forEach(dataINfo => {
            dataINfo.draw();
        })
    }

    setOption(options){
        // this.options = {
        //     year:options.year || [2012,2013,2014,2015,2016,2017,2018,2019,2020],
        //     data:options.data || [
        //         {
        //             year:2015,
        //             text:'百度消毒机器人'
        //         },
        //         {
        //             year:2016,
        //             text:'我是天才我要在这里测试谢谢'
        //         },
        //         {
        //             year:2017,
        //             text:'依然高亚杰水电费设计的飞机上的'
        //         }
        //     ]
        // };
        this.options = {
            year:options.year,
            data:options.data
        };
        this.restoreDraw();
    }

    restoreDraw(){
        // 清屏
        this.clearScreen();

        this.drawSplipt();
        this.drawYear();
        this.drawData();
    }

    destroyed() {
         this.canvas.onmousedown = null;
         this.canvas.onmousemove = null;
         document.onmouseup = null;
        // this.tooltip.remove();
         this.tooltip = null;
    }
}

class Datainfo {
    ctx = null;
    x = 0;
    y = 0;
    cx = 0;
    cy = 0;
    text = "";
    index = 0;
    color = ['#fe01fd','#f59f00','#00ff00','#fe01fd','#0066ff','#00a8ff'];

    constructor({ctx,x,y,cx,cy,text,index}){
        this.ctx = ctx;
        this.x = x;
        this.y = y;
        this.cx = cx;
        this.cy = cy;
        this.text = text;
        this.index = index;
    }
    draw() {
        let ctx = this.ctx,text = this.text,x = this.x,y = this.y,index = this.index,color = this.color,cx = this.cx;

        if(index % 2 == 0){
            ctx.save();
            ctx.strokeStyle = color[index%color.length];
            ctx.fillStyle = color[index%color.length];
            // 画桃形状
            let dx = 6;
            let dy = 9
            ctx.beginPath()
            ctx.moveTo(cx + x,y - 20);
            ctx.lineTo(cx + x + dx, y - 20 - dy);
            ctx.arcTo(cx + x + dx, y - 20 - (dy + dx),cx + x,y - 20 - (dy + dx), dx); 
            ctx.arcTo(cx+x - dx ,y - 20 - (dy + dx),cx+x - dx ,y - 20 , dx); 
            ctx.lineTo(cx+x,y - 20);
            ctx.fill();

            // 画线
            ctx.beginPath();
            ctx.moveTo(cx + x,y - 20 - dx -dy);
            ctx.lineTo(cx + x,y - 60);
            ctx.stroke()
            // 画字
            this.drawText(text,cx+x,y-60,50,-10);
            // ctx.textAlign = "left";    
            // ctx.fillStyle = "#98caec"; //设置字体对齐的方式
            // let fontW = ctx.measureText(text).width;

            // ctx.fillText(text, x - fontW/2 , y - 70);
            ctx.restore();
        }else{
            ctx.save();
            ctx.strokeStyle = color[index%color.length];
            ctx.fillStyle = color[index%color.length];
            // 画桃形状
            let dx = 6;
            let dy = 9
            ctx.beginPath()
            ctx.moveTo(cx + x,y + 20);
            ctx.lineTo(cx + x + dx, y + 20 + dy);
            ctx.arcTo(cx + x + dx, y + 20 + (dy + dx),cx + x,y + 20 + (dy + dx), dx); 
            ctx.arcTo(cx+ x - dx ,y + 20 + (dy + dx),cx+ x - dx ,y + 20 , dx); 
            ctx.lineTo(cx + x,y + 20);
            ctx.fill();

            // 画线
            ctx.beginPath();
            ctx.moveTo(cx + x,y +20 + dx + dy);
            ctx.lineTo(cx + x,y + 60);
            ctx.stroke()

            // 书写文字
            // ctx.textAlign = "left";    
            // ctx.fillStyle = "#98caec"; //设置字体对齐的方式
            // let fontW = ctx.measureText(text).width;
            // ctx.fillText(text, x - fontW/2 , y + 70);
            this.drawText(text,cx+x,y+60,50,10)

            ctx.restore();
        }
            

    }

    drawText(t, x, y, w,l) {
        let ctx = this.ctx;
        ctx.save()
        var chr = t.split("");
        var temp = "";
        var row = [];
        ctx.font = "10px Arial";
        ctx.fillStyle = "#98caec";
        ctx.textBaseline = "middle";

        for (var a = 0; a < chr.length; a++) {
            if (ctx.measureText(temp).width < w) {;
            } else {
                row.push(temp);
                temp = "";
            }
            temp += chr[a];
        }

        row.push(temp);
        
        for (var b = 0; b < row.length; b++) {
            if(l > 0) {
                let fontW = ctx.measureText(row[b]).width;
                ctx.fillText(row[b], x - fontW/2, y + (b + 1) * l);
            }else {
                let fontW = ctx.measureText(row[b]).width;
                ctx.fillText(row[b], x - fontW/2, y + (row.length -b) * l);
            }
           
        }
        ctx.restore();
    }
}

const timeshistory = new Timeshistory();

export default timeshistory;